<template>
  <div class="bgc-white" style="display: flex">
    <div class="p16" style="width: 300px; flex-shrink: 0">
      <div class="flex-center-between">
        <span class="fs16 fw500">销售分组</span>
        <span style="display: inline-block; cursor: pointer" @click="onAddGroupItem">
          <a-icon type="plus" />
        </span>
      </div>
      <div class="mt12">
        <a-input-search placeholder="搜索分组" style="width: 268px" allowClear @change="onGroupSearchChange" />
      </div>
      <div
        v-if="groupSite"
        class="mt24 ph8 pv4 flex-center-between"
        style="border-bottom: 1px solid #e8e8e8; cursor: pointer; border-radius: 4px"
        :style="{
          background: groupSite.id === currentGroupId ? 'var(--primary30)' : 'transparent'
        }"
        @click="onGroupChange(groupSite.id)"
      >
        <span>{{ groupSite.name }}（{{ groupSite.count }}）</span>
        <span v-if="groupSite.editable" @click.stop="onEditGroupItem(groupSite.id)" style="cursor: pointer">
          <a-icon type="setting" />
        </span>
        <span v-else style="color: rgba(0, 0, 0, 0.15)">
          <a-icon type="setting" />
        </span>
      </div>
      <div class="mt8" style="width: 100%; overflow-x: auto">
        <a-tree
          :treeData="groupSubTree"
          :selectedKeys="[currentGroupId]"
          defaultExpandAll
          @select="(selectedKeys) => onGroupChange(selectedKeys[0])"
        >
          <template slot="title" slot-scope="node">
            <div class="flex-center">
              <div class="ellipsis" style="width: 200px">{{ node.title }}（{{ node.count }}）</div>
              <a-icon v-if="node.editable" type="setting" @click.stop="onEditGroupItem(node.value)" />
              <a-icon v-else type="setting" style="color: rgba(0, 0, 0, 0.15)" />
            </div>
          </template>
        </a-tree>
      </div>
    </div>
    <div class="p16" style="flex: 1; border-left: 1px solid #e8e8e8">
      <template v-if="currentGroupTarget">
        <div>
          <span class="fs16 fw500 mr8">{{ currentGroupTarget.name }}</span>
          <span v-if="currentGroupTarget.groupSupervisor">分组主管：{{ currentGroupTarget.groupSupervisor }}</span>
        </div>
        <div v-if="currentGroupTarget.description" class="fs12 mt12" style="color: rgba(102, 102, 102, 1)">
          {{ currentGroupTarget.description }}
        </div>
      </template>
      <div class="flex-center-between mt16">
        <a-space>
          <a-input-search
            v-model="saleNameOrPhoneOrIdCard"
            placeholder="销售名称/联系电话/身份证号"
            allowClear
            style="width: 230px"
            @change="onEmpSearchChange"
          />
          <a-cascader
            v-model="region"
            :options="common.areaList"
            changeOnSelect
            placeholder="所在地区"
            :show-search="{ filter }"
            allowClear
            style="width: 120px"
            @change="onEmpSearchChange"
          />
          <a-select v-model="isCurrentGroup" placeholder="显示成员" style="width: 180px" @change="onEmpSearchChange">
            <a-select-option value="0">显示全部分组成员</a-select-option>
            <a-select-option value="1">仅显示当前部门成员</a-select-option>
          </a-select>
        </a-space>
        <a-space>
          <a-button @click="onExportEmp">全部导出</a-button>
          <a-button type="primary" @click="onAddEmpItem"><a-icon type="plus" />新增销售</a-button>
        </a-space>
      </div>
      <a-table
        :dataSource="empLst"
        :pagination="pagination"
        :columns="empColumns"
        rowKey="id"
        size="middle"
        class="mt16"
        @change="onEmpTableChange"
      >
        <a-space slot="action" slot-scope="text, record">
          <a @click="onEditEmpItem(record)">编辑</a>
          <a @click="onDelEmpItem(record.id)">删除</a>
        </a-space>
        <template slot="uc" slot-scope="text, record">
          <div class="ellipsis pointer" style="width: 200px" @click="$refs.uc.onItemClick(record.saleUserId)">
            <a>{{ text }}</a>
          </div>
        </template>
      </a-table>
    </div>
    <a-modal v-model="groupModalVisible" :title="groupModalTitle">
      <a-form :form="groupForm">
        <a-form-item v-if="!disabled" label="选择上层分组" :labelCol="{ span: 7 }" :wrapperCol="{ span: 14 }">
          <a-tree-select
            v-decorator="['parentId', { rules: [{ required: true, message: '必须选择上层分组' }] }]"
            :treeData="groupFullTree"
            showSearch
            treeNodeFilterProp="title"
            placeholder="请选择"
            style="width: 100%"
            @select="onGroupParentChange"
          />
        </a-form-item>
        <a-form-item label="分组名称" :labelCol="{ span: 7 }" :wrapperCol="{ span: 14 }">
          <a-input
            v-decorator="['name', { rules: [{ required: true, message: '必须填写名称' }] }]"
            :disabled="disabled"
            placeholder="请输入"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="分组主管" :labelCol="{ span: 7 }" :wrapperCol="{ span: 14 }">
          <a-select
            v-decorator="['groupSupervisor']"
            :options="groupManagers"
            showSearch
            :filterOption="filterOption"
            :disabled="tempGroup && tempGroup.editAdminPermissions !== true"
            optionFilterProp="label"
            mode="multiple"
            placeholder="请选择"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="分组说明" :labelCol="{ span: 7 }" :wrapperCol="{ span: 14 }">
          <a-textarea v-decorator="['description']" placeholder="请输入" style="width: 100%" />
        </a-form-item>
      </a-form>
      <a-space slot="footer">
        <a-button @click="groupModalVisible = false">取消</a-button>
        <a-button v-if="groupModalTitle === '编辑分组'" :disabled="disabled" type="danger" @click="onDelGroupItem">删除</a-button>
        <a-button :loading="confirmLoadingGroup" type="primary" @click="onGroupModalOk">提交</a-button>
      </a-space>
    </a-modal>
    <a-modal v-model="empModalVisible" :title="empModalTitle" :confirmLoading="confirmLoadingEmp" @ok="onEmpModalOk">
      <a-form :form="empForm">
        <a-form-item label="所属分组" :labelCol="{ span: 7 }" :wrapperCol="{ span: 14 }">
          <a-tree-select
            v-decorator="['saleGroupId', { rules: [{ required: true, message: '必须选择所属分组' }] }]"
            :treeData="groupSubTree"
            showSearch
            treeNodeFilterProp="title"
            placeholder="请选择"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="销售名称" :labelCol="{ span: 7 }" :wrapperCol="{ span: 14 }">
          <a-select
            v-decorator="['saleUserId', { rules: [{ required: true, message: '必须选择销售' }] }]"
            :options="groupManagers2"
            :disabled="!!tempEmp"
            showSearch
            :filterOption="filterOption"
            optionFilterProp="label"
            placeholder="请选择"
            style="width: 100%"
            @change="onEmpChange"
          />
        </a-form-item>
        <a-form-item label="联系电话" :labelCol="{ span: 7 }" :wrapperCol="{ span: 14 }">
          <a-input
            v-decorator="['salePhone', { rules: [{ required: true, message: '必须填写联系电话' }] }]"
            disabled
            placeholder="请选择销售"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="所在地区" :labelCol="{ span: 7 }" :wrapperCol="{ span: 14 }">
          <a-cascader
            v-decorator="['region']"
            :options="common.areaList"
            :show-search="{ filter }"
            changeOnSelect
            placeholder="请选择"
            style="width: 100%"
            @change="onRegionChange"
          />
        </a-form-item>
        <a-form-item label="身份证号" :labelCol="{ span: 7 }" :wrapperCol="{ span: 14 }">
          <a-input v-decorator="['saleIdCard']" placeholder="请填写" style="width: 100%" />
        </a-form-item>
        <a-form-item label="银行卡号" :labelCol="{ span: 7 }" :wrapperCol="{ span: 14 }">
          <a-input v-decorator="['saleBankCard']" placeholder="请填写" style="width: 100%" />
        </a-form-item>
      </a-form>
    </a-modal>
    <UserCompany ref="uc" />
  </div>
</template>
<script>
import { queryUserListLessToMeReq, queryUserListLessToMeAddReq } from "../api";
import { selectGroupTreeReq, saveGroupReq, updateGroupReq, deleteGroupReq, selectGroupInfoReq } from "../api";
import { saleUsersReq, selectSaleByGroupIdReq, delSaleUsersReq, updateSaleUsersReq, exportSaleUsersReq } from "../api";
import { formatGroupTreeForXS, empColumns, formatRegionValueDe, formatRegionValueEn } from "../funcs";
import { mapState } from "vuex";
import UserCompany from "../components/userCompany.vue";
export default {
  name: "",
  components: { UserCompany },
  mixins: [],
  props: {},
  data() {
    return {
      disabled: false,
      empColumns,
      groupModalTitle: "添加分组",
      groupForm: this.$form.createForm(this),
      groupSite: null,
      groupSubTree: [],
      groupFullTree: [],
      groupModalVisible: false,
      groupManagers: [],
      groupManagersMap: {},
      groupManagers2: [],
      tempGroup: null,
      tempGroupParent: null,
      currentGroupId: null,
      currentGroupTarget: null,
      empModalTitle: "添加销售",
      empModalVisible: false,
      empForm: this.$form.createForm(this),
      tempEmp: null,
      tempEmpForSelect: null,
      empLst: [],
      pagination: {
        pageSize: 10,
        total: 0,
        size: "default",
        current: 1,
        showTotal: (total) => `共 ${total} 条`,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ["10", "20", "50", "100"]
      },
      saleNameOrPhoneOrIdCard: "",
      region: undefined,
      isCurrentGroup: "0",
      confirmLoadingEmp: false,
      confirmLoadingGroup: false,
      empRegionTemp: null
    };
  },
  computed: {
    ...mapState(["common"]),
    areaSourceMap() {
      return this.common.areaSourceMap;
    }
  },
  watch: {
    currentGroupId() {
      this.pagination.current = 1;
      this.onEmpSearchChange();
    }
  },
  created() {},
  mounted() {
    this.onGroupSearchChange();
    this.queryUserListLessToMeAddMed();
    this.queryUserListLessToMeMed();
  },
  methods: {
    filter(inputValue, path) {
      return path.some((option) => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
    },
    onDelEmpItem(empId) {
      this.$confirm({
        title: "删除提示",
        content: "记录删除后将无法恢复，确认要删除吗？",
        onOk: () => {
          delSaleUsersReq(empId)
            .then((res) => {
              this.$message.success("删除成功");
              this.onEmpSearchChange();
              this.onGroupSearchChange();
            })
            .catch((err) => {
              console.log("delSaleUsersReq", err);
            });
        }
      });
    },
    onEmpTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.onEmpSearchChange();
    },
    onExportEmp() {
      const params = {
        groupId: this.currentGroupId,
        isCurrentGroup: this.isCurrentGroup === "1"
      };
      if (this.saleNameOrPhoneOrIdCard) {
        params["saleNameOrPhoneOrIdCard"] = this.saleNameOrPhoneOrIdCard;
      }
      if (this.region) {
        params["region"] = this.region[this.region.length - 1];
      }
      exportSaleUsersReq(params)
        .then((res) => {
          if (res.data && res.data.type === "application/json") {
            const reader = new FileReader();
            reader.readAsText(res.data, "utf-8");
            reader.onload = () => {
              const resJson = JSON.parse(reader.result);
              this.$message.error(resJson.msg);
            };
          } else {
            const blob = new Blob([res.data], { type: "application/octet-stream" });
            const link = document.createElement("a");
            link.download = "销售列表.xlsx";
            link.href = URL.createObjectURL(blob);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
          }
        })
        .catch((err) => {
          console.log("selectSaleByGroupIdReq", err);
        });
    },
    onEmpSearchChange() {
      const params = {
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        groupId: this.currentGroupId,
        isCurrentGroup: this.isCurrentGroup === "1"
      };
      if (this.saleNameOrPhoneOrIdCard) {
        params["saleNameOrPhoneOrIdCard"] = this.saleNameOrPhoneOrIdCard;
      }
      if (this.region) {
        params["region"] = this.region[this.region.length - 1];
      }
      selectSaleByGroupIdReq(params)
        .then((res) => {
          this.empLst = res.data.entities;
          this.pagination.total = res.data.entityCount;
        })
        .catch((err) => {
          console.log("selectSaleByGroupIdReq", err);
        });
    },
    onEmpModalOk() {
      this.empForm.validateFields((err, values) => {
        if (!err) {
          const newValues = {
            saleUserId: values.saleUserId,
            salePhone: values.salePhone,
            saleBankCard: values.saleBankCard,
            saleIdCard: values.saleIdCard,
            saleGroupId: values.saleGroupId
          };
          this.confirmLoadingEmp = true;
          if (this.empModalTitle === "添加销售") {
            newValues["saleName"] = this.tempEmpForSelect.name;
            newValues["region"] = formatRegionValueEn(this.empRegionTemp);
            saleUsersReq(newValues)
              .then((res) => {
                this.$message.success("添加成功");
                this.pagination.current = 1;
                this.onEmpSearchChange();
                this.empModalVisible = false;
                this.confirmLoadingEmp = false;
                this.onGroupSearchChange();
              })
              .catch((err) => {
                console.log("saleUsersReq", err);
                this.confirmLoadingEmp = false;
              });
          } else {
            newValues["id"] = this.tempEmp.id;
            newValues["saleName"] = this.tempEmp.saleName;
            newValues["region"] = formatRegionValueEn(this.empRegionTemp) || this.tempEmp.region;
            updateSaleUsersReq(newValues)
              .then((res) => {
                this.$message.success("修改成功");
                this.onEmpSearchChange();
                this.empModalVisible = false;
                this.confirmLoadingEmp = false;
              })
              .catch((err) => {
                console.log("updateSaleUsersReq", err);
                this.confirmLoadingEmp = false;
              });
          }
        }
      });
    },
    onEditEmpItem(target) {
      this.empRegionTemp = null;
      this.tempEmp = target;
      this.empModalTitle = "编辑销售";
      this.empModalVisible = true;
      this.$nextTick(() => {
        this.empForm.setFieldsValue({
          saleGroupId: target.saleGroupId,
          saleUserId: target.saleUserId,
          salePhone: target.salePhone,
          saleIdCard: target.saleIdCard,
          saleBankCard: target.saleBankCard,
          region: formatRegionValueDe(target.region)
        });
      });
    },
    onAddEmpItem() {
      this.empRegionTemp = null;
      this.empForm.resetFields();
      this.empModalTitle = "添加销售";
      this.tempEmp = null;
      this.empModalVisible = true;
    },
    onEmpChange(value, selectedOptions) {
      this.tempEmpForSelect = {
        id: value,
        name: selectedOptions.data.props.name,
        phone: selectedOptions.data.props.phone
      };
      this.empForm.setFieldsValue({
        salePhone: this.tempEmpForSelect.phone,
        saleIdCard: "",
        saleBankCard: "",
        region: undefined
      });
    },
    onRegionChange(value, selectedOptions) {
      this.empRegionTemp = selectedOptions;
    },
    async onGroupChange(theKey) {
      if (theKey) {
        const target = await selectGroupInfoReq(theKey)
          .then((res) => {
            return res.data;
          })
          .catch((err) => {
            console.log("selectGroupInfoReq", err);
            return false;
          });
        if (target) {
          this.currentGroupTarget = {
            name: target.name,
            description: target.description,
            groupSupervisor: target.groupSupervisor ? target.groupSupervisor.map((li) => li.name).join("、") : ""
          };
        }
        this.currentGroupId = theKey;
      }
    },
    onDelGroupItem() {
      this.$confirm({
        title: "删除确认",
        content: "分组删除后将无法恢复，确认要删除吗？",
        onOk: () => {
          deleteGroupReq(this.tempGroup.id)
            .then(() => {
              this.$message.success("删除成功");
              this.onGroupSearchChange();
              this.groupModalVisible = false;
            })
            .catch((err) => {
              console.log("deleteGroupReq", err);
            });
        }
      });
    },
    onGroupParentChange(val, node) {
      this.tempGroupParent = node.dataRef;
    },
    onGroupModalOk() {
      this.groupForm.validateFields((err, values) => {
        if (!err) {
          const newValues = {
            name: values.name,
            description: values.description,
            parentId: values.parentId || "0",
            level: this.tempGroupParent ? this.tempGroupParent.level + 1 : this.tempGroup.level
          };
          if (values.groupSupervisor && values.groupSupervisor.length > 0) {
            newValues["groupSupervisor"] = values.groupSupervisor.map((val) => ({
              id: this.groupManagersMap[val].value,
              name: this.groupManagersMap[val].label,
              phone: this.groupManagersMap[val].phone
            }));
          }
          this.confirmLoadingGroup = true;
          if (this.groupModalTitle === "添加分组") {
            newValues["groupType"] = "sale";
            newValues["sort"] = 1;
            saveGroupReq(newValues)
              .then((res) => {
                this.$message.success("添加成功");
                this.onGroupSearchChange();
                this.groupModalVisible = false;
                this.confirmLoadingGroup = false;
              })
              .catch((err) => {
                this.confirmLoadingGroup = false;
                console.log("saveGroupReq", err);
              });
          } else {
            updateGroupReq({
              ...newValues,
              id: this.tempGroup.id
            })
              .then((res) => {
                this.$message.success("修改成功");
                this.onGroupSearchChange();
                this.groupModalVisible = false;
                this.confirmLoadingGroup = false;
              })
              .catch((err) => {
                this.confirmLoadingGroup = false;
                console.log("updateGroupReq", err);
              });
          }
        }
      });
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    queryUserListLessToMeAddMed() {
      queryUserListLessToMeAddReq()
        .then((res) => {
          const tempList = [];
          const tempMap = {};
          for (let i = 0; i < res.data.length; i++) {
            const newItem = {
              value: res.data[i].id,
              label: res.data[i].name,
              name: res.data[i].name,
              phone: res.data[i].phone
            };
            tempMap[newItem.value] = newItem;
            tempList.push(newItem);
          }
          this.groupManagers = tempList;
          this.groupManagersMap = tempMap;
        })
        .catch((err) => {
          console.log("queryUserListLessToMeAddReq", err);
        });
    },
    queryUserListLessToMeMed() {
      queryUserListLessToMeReq()
        .then((res) => {
          const tempList = [];
          for (let i = 0; i < res.data.length; i++) {
            const newItem = {
              value: res.data[i].id,
              label: res.data[i].name,
              name: res.data[i].name,
              phone: res.data[i].phone
            };
            tempList.push(newItem);
          }
          this.groupManagers2 = tempList;
        })
        .catch((err) => {
          console.log("queryUserListLessToMeReq", err);
        });
    },
    async onEditGroupItem(groupId) {
      const target = await selectGroupInfoReq(groupId)
        .then((res) => {
          return res.data;
        })
        .catch((err) => {
          console.log("selectGroupInfoReq", err);
          return false;
        });
      if (target) {
        if (target.parentId === "0") {
          this.disabled = true;
        } else {
          this.disabled = false;
        }
        this.tempGroup = target;
        this.groupModalTitle = "编辑分组";
        this.groupModalVisible = true;
        const groupSupervisorIds = target.groupSupervisor ? target.groupSupervisor.map((li) => li.id) : [];
        setTimeout(() => {
          const temp = {
            name: target.name,
            description: target.description,
            groupSupervisor: groupSupervisorIds
          };
          if (!this.disabled) {
            temp["parentId"] = target.parentId;
          }
          this.groupForm.setFieldsValue(temp);
        }, 0);
      } else {
        this.$message.error("查询分组详情失败");
      }
    },
    onAddGroupItem() {
      this.disabled = false;
      this.groupForm.resetFields();
      this.groupModalTitle = "添加分组";
      this.tempGroup = null;
      this.tempGroupParent = null;
      this.groupModalVisible = true;
    },
    onGroupSearchChange(e) {
      const p = e ? e.target.value : null;
      selectGroupTreeReq(p)
        .then((res) => {
          this.groupSite = {
            id: res.data[0].id,
            name: res.data[0].name,
            count: res.data[0].memberCount || 0,
            editable: res.data[0].havePermissions === true
          };
          this.groupSubTree = formatGroupTreeForXS(res.data[0].childList, true);
          if (!p) {
            this.groupFullTree = formatGroupTreeForXS(res.data, true);
          }
          if (!this.currentGroupId) {
            this.currentGroupId = this.groupSite.id;
            this.onGroupChange(this.groupSite.id);
          }
        })
        .catch((err) => {
          console.log("selectGroupTreeReq", err);
        });
    }
  }
};
</script>
<style lang="scss"></style>
